<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">




  
  
    
    
  <script src="/ikaros/lib/pace/pace.min.js?v=1.0.2"></script>
  <link rel="stylesheet" href="/ikaros/lib/pace/pace-theme-minimal.min.css?v=1.0.2">





















<link rel="stylesheet" href="/ikaros/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/ikaros/css/main.css?v=7.0.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/ikaros/images/favicon.ico?v=7.0.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/ikaros/images/favicon.ico?v=7.0.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/ikaros/images/favicon.ico?v=7.0.1">








<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/ikaros/',
    scheme: 'Gemini',
    version: '7.0.1',
    sidebar: {"position":"left","display":"post","offset":6,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="基于Nginx和Gunicorn自动化部署Django博客网站（心得教程）阅前叨逼叨众所周知，基于PHP的网站部署到服务器上，目前有很多一站式的Web管理，比如：宝塔Linux，一键创建网站、FTP、数据库，连免费的SSL能帮你做好了，一键打上证书，成了！简直不要太方便！可我偏偏就选择了用Python+Django来做这个博客，当准备往服务器上部署的时候，各种各样的坑就来了。最后网站倒是上线了，只">
<meta name="keywords" content="Python,Linux,learn">
<meta property="og:type" content="article">
<meta property="og:title" content="基于Nginx和Gunicorn自动化部署Django博客网站（心得教程）">
<meta property="og:url" content="http://ikarosyu.gitee.io/ikaros/2019/02/28/Nginx-Gunicorn/index.html">
<meta property="og:site_name" content="ikaros&#39;blog">
<meta property="og:description" content="基于Nginx和Gunicorn自动化部署Django博客网站（心得教程）阅前叨逼叨众所周知，基于PHP的网站部署到服务器上，目前有很多一站式的Web管理，比如：宝塔Linux，一键创建网站、FTP、数据库，连免费的SSL能帮你做好了，一键打上证书，成了！简直不要太方便！可我偏偏就选择了用Python+Django来做这个博客，当准备往服务器上部署的时候，各种各样的坑就来了。最后网站倒是上线了，只">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://ikarosyu.gitee.io/ikaros/2019/02/28/Nginx-Gunicorn/1.jpg">
<meta property="og:image" content="http://ikarosyu.gitee.io/ikaros/2019/02/28/Nginx-Gunicorn/2.jpg">
<meta property="og:updated_time" content="2019-03-19T10:58:37.720Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="基于Nginx和Gunicorn自动化部署Django博客网站（心得教程）">
<meta name="twitter:description" content="基于Nginx和Gunicorn自动化部署Django博客网站（心得教程）阅前叨逼叨众所周知，基于PHP的网站部署到服务器上，目前有很多一站式的Web管理，比如：宝塔Linux，一键创建网站、FTP、数据库，连免费的SSL能帮你做好了，一键打上证书，成了！简直不要太方便！可我偏偏就选择了用Python+Django来做这个博客，当准备往服务器上部署的时候，各种各样的坑就来了。最后网站倒是上线了，只">
<meta name="twitter:image" content="http://ikarosyu.gitee.io/ikaros/2019/02/28/Nginx-Gunicorn/1.jpg">



  <link rel="alternate" href="/ikaros/atom.xml" title="ikaros'blog" type="application/atom+xml">




  <link rel="canonical" href="http://ikarosyu.gitee.io/ikaros/2019/02/28/Nginx-Gunicorn/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>基于Nginx和Gunicorn自动化部署Django博客网站（心得教程） | ikaros'blog</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/ikaros/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">ikaros'blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">平安喜乐</p>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/ikaros/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/ikaros/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/ikaros/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/ikaros/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/ikaros/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    
  
  
  
  

  

  <a href="https://github.com/ikarosyu" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewbox="0 0 250 250" style="fill: #222; color: #fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a>



    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://ikarosyu.gitee.io/ikaros/ikaros/2019/02/28/Nginx-Gunicorn/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ikaros">
      <meta itemprop="description" content="like sunday like rain like apple and cinnamon">
      <meta itemprop="image" content="/ikaros/images/Misaka.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="ikaros'blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">基于Nginx和Gunicorn自动化部署Django博客网站（心得教程）

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-02-28 16:09:52" itemprop="dateCreated datePublished" datetime="2019-02-28T16:09:52+08:00">2019-02-28</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-03-19 18:58:37" itemprop="dateModified" datetime="2019-03-19T18:58:37+08:00">2019-03-19</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/ikaros/categories/develop/" itemprop="url" rel="index"><span itemprop="name">develop</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon">
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">9.3k</span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">8 分钟</span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="基于Nginx和Gunicorn自动化部署Django博客网站（心得教程）"><a href="#基于Nginx和Gunicorn自动化部署Django博客网站（心得教程）" class="headerlink" title="基于Nginx和Gunicorn自动化部署Django博客网站（心得教程）"></a>基于Nginx和Gunicorn自动化部署Django博客网站（心得教程）</h1><h2 id="阅前叨逼叨"><a href="#阅前叨逼叨" class="headerlink" title="阅前叨逼叨"></a>阅前叨逼叨</h2><p>众所周知，基于PHP的网站部署到服务器上，目前有很多一站式的Web管理，比如：宝塔Linux，一键创建网站、FTP、数据库，连免费的SSL能帮你做好了，一键打上证书，成了！简直不要太方便！可我偏偏就选择了用Python+Django来做这个博客，当准备往服务器上部署的时候，各种各样的坑就来了。最后网站倒是上线了，只是感觉头顶凉飕飕的…</p>
<h2 id="首要的准备"><a href="#首要的准备" class="headerlink" title="首要的准备"></a>首要的准备</h2><p>在这里我们准备使用当下较为流行的Nginx+Gunicorn方式来把我们的Django博客部署到服务器上，然后通过域名来访问我们的网站。</p>
<a id="more"></a>
<p>（提取关键词）服务器、域名，这便是我们做这项工作的首要准备：</p>
<ol>
<li>一台可以通过外网访问的服务器。</li>
<li>一个自己的域名（最好备过案，没有备案也无伤大雅）。</li>
<li>一颗勇敢的心，遇坑不要怕，你遇到的坑99.9%网上都能够找到答案。</li>
</ol>
<p>下面介绍一下这三点准备：</p>
<h3 id="服务器"><a href="#服务器" class="headerlink" title="服务器"></a>服务器</h3><p>现在阿里云、腾讯云都在大力发展这方面的服务，全民建站嘛。而如果你是学生，那么9.9包月不是梦，我购买的：<a href="https://promotion.aliyun.com/ntms/act/campus2018.html" target="_blank" rel="noopener">轻量型应用服务器</a>(刚看了一下，已经9.5了)，1核2G、5M带宽、40G系统SSG盘，对于个人网站已经是绰绰有余了。简简单单的购买成功后，推荐安装系统镜像 Ubuntu 16.04，当然CentOS也能够使用Nginx + Gunicorn来完成部署，只不过系统命令有一些不同，如又需要可以自行研究。<strong>本心得教程完全基于Ubuntu 16.04。</strong></p>
<p>阿里云、腾讯云其他的服务器土豪请随意挑选，能够满足您的所有要求。</p>
<p>如果你不是学生，也不是什么什么二代，那么可以购买国外的服务器。有很多很便宜的服务器，我甚至还听说续期不要钱，不过每天都要上服务器使用一次，只要你能坚持…至于如何购买，我就不介绍了，只能说有能力的都买了。这类服务器可能性能就比不上阿里云、腾讯云的，但是你可以用它来搭梯子啊，VPN封的那么厉害，我用SS或者SSR就好了嘛（小声逼逼）。最后系统依旧选择Ubuntu 16.04。</p>
<h3 id="域名购买"><a href="#域名购买" class="headerlink" title="域名购买"></a>域名购买</h3><p>域名，也就是网域名称系统，是因特网的一项核心服务，它作为可以将域名和<a href="https://baike.baidu.com/item/IP%E5%9C%B0%E5%9D%80" target="_blank" rel="noopener">IP地址</a>相互<a href="https://baike.baidu.com/item/%E6%98%A0%E5%B0%84/410062" target="_blank" rel="noopener">映射</a>的一个分布式数据库，能够使人更方便的访问互联网，而不用去记住能够被机器直接读取的IP地址数串。</p>
<p>在我们购买阿里云、腾讯云服务器的时候便能够购买域名，如： <a href="https://wanwang.aliyun.com/domain/" target="_blank" rel="noopener">阿里云域名注册系统</a>。我的域名是在购买第一个服务器时加1毛钱送的，第二年续费就的加钱了。有很多很便宜的域名，如果只是为了测试，随便注册一个域名即可，但注意一点根据工信部规定，以下后缀的域名需要实名认证后才能使用：</p>
<blockquote>
<p>.cn/.com/.net/.top/.xyz/.vip/.club/.ren/.wang/.shop/.xin/.中国/.信息/.公司/.网络/.广东/.佛山</p>
</blockquote>
<p>如果你购买的是上述后缀的域名，意味着需要提交个人的身份资料实名认证后才能正常使用，这通常需要花费几天的时间。<strong>所以如果只为了测试和学习部署的话，最好避开上述后缀的域名。</strong></p>
<h2 id="搭建服务器"><a href="#搭建服务器" class="headerlink" title="搭建服务器"></a>搭建服务器</h2><p>前提：本心得教程本地使用Window10为环境，服务器端使用Ubuntu 16.04。</p>
<p>在阿里云购买服务器后，网页自带服务器连接功能，无需使用Xshell等工具连接。但是要连接到服务器首先要进入你的服务器的监控页面，如果嫌麻烦，可下载安装Xshell进行服务器连接。具体操作这里就不赘述了，网上有很多教程能够帮到你。</p>
<h3 id="安装软件"><a href="#安装软件" class="headerlink" title="安装软件"></a>安装软件</h3><p>连接到服务器后，一般是以root用户登陆的。而为了网站的安全维护，我们一般不选择在root下部署代码。这里我们新建一个用户Django，并将它加入超级用户组：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">#登陆到root用户后，在root用户下新建一个用户，Django是用户名</span><br><span class="line">#因为博客是基于Python的Django包搭建的，所以这里就用了Django作为名字</span><br><span class="line">#你可以使用自己喜欢的名字，不一定要和我一样</span><br><span class="line">root@localhost:~# useradd -m -s /bin/bash django</span><br><span class="line"></span><br><span class="line">#设置用户的密码</span><br><span class="line">#Ubuntu包括CentOS秉承着没有反馈就是最好的反馈，只要没有任何提示，那么你输入的命令就没有问题，不要以为系统什么都没有做</span><br><span class="line">#输密码的时候不会有字符显示，不要以为键盘坏了，正常输入即可</span><br><span class="line">root@localhost:~# passwd django</span><br><span class="line"></span><br><span class="line">#切换到新建的用户</span><br><span class="line">root@localhost:~# su - django</span><br><span class="line"></span><br><span class="line">#这时候@符号前面的用户名就换成了django</span><br><span class="line">django@localhost:~$</span><br></pre></td></tr></table></figure>
<p>新用户创建成功后，只是为了能够在新用户的地址下部署代码，不一定非要切换到新用户在执行操作，因为有可能是Ubuntu 16.04的原因，虽然我把django加入到了超级用户组。但是有一些命令执行时任然提示权限不够，我目前还没有找到解决的办法，为了你我能够避开这些坑，以下的操作建议任然在root用户下执行，毕竟Ubuntu认为root才是老大…</p>
<p>下面我们为了避免所使用Ubuntu系统版本太旧而给后面安装软件带来麻烦，我们在使用前先更新一下。运行一下命令：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">root@localhost:~$ sudo apt-get update</span><br><span class="line">root@localhost:~$ sudo apt-get upgrade</span><br></pre></td></tr></table></figure>
<p>耐心等待一会儿，更新完成后，我们就开始安装需要用到的软件：Nginx、Pytohn3、Git、pip 和 virtualenv。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">root@localhost:~$ root@localhost:~$</span><br><span class="line">root@localhost:~$ sudo apt-get install git python3 python3-pip</span><br><span class="line">root@localhost:~$ sudo pip3 install virtualenv</span><br></pre></td></tr></table></figure>
<h3 id="解析域名到服务器的IP地址"><a href="#解析域名到服务器的IP地址" class="headerlink" title="解析域名到服务器的IP地址"></a>解析域名到服务器的IP地址</h3><p>在阿里云服务器的管理控制台，能够直接将你已经购买的域名进行解析，具体操作参阿里云域名解析服务。注意：需要备案的域名，大多数要先备案才能够解析，部分地区除外。</p>
<p>将域名和服务器的 IP 地址绑定后，用户就可以通过在浏览器输入域名来访问服务器了。下图是我的域名和服务器的 IP 地址绑定：</p>
<p><img src="/ikaros/2019/02/28/Nginx-Gunicorn/1.jpg" alt></p>
<h3 id="启动Nginx服务"><a href="#启动Nginx服务" class="headerlink" title="启动Nginx服务"></a>启动Nginx服务</h3><p>Nginx 是用来处理静态文件请求的。比如当我们访问一个博客文章详情页面时，服务器会接收到下面两种请求：</p>
<ul>
<li>显示文章的详情信息，这些信息通常保存在数据库里，因此需要调用数据库获取数据。</li>
<li>图片、css、js 等存在服务器某个文件夹下的静态文件。</li>
</ul>
<p>对于前一种请求，博客文章的数据需要借助 Django 从数据库中获取，Nginx 处理不了，它就会把这个请求转发给 Django，让 Django 去处理。而对于后一种静态文件的请求，只需要去这些静态文件所在的文件夹获取，Nginx 就会代为处理，不再麻烦 Django。</p>
<p>用 Django 去获取静态文件是很耗时的，但 Nginx 可以很高效地处理，这就是我们要使用 Nginx 的原因，当然其功能远不止这些。</p>
<p>运行下面的命令来启动我们已经安装的Nginx服务：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">root@localhost:~$ sudo service nginx start</span><br></pre></td></tr></table></figure>
<p>然后我们在浏览器输入域名，当看到下面的界面说明Nginx启动成功了，</p>
<p><img src="/ikaros/2019/02/28/Nginx-Gunicorn/2.jpg" alt></p>
<h2 id="代码的部署"><a href="#代码的部署" class="headerlink" title="代码的部署"></a>代码的部署</h2><h3 id="部署前的项目配置"><a href="#部署前的项目配置" class="headerlink" title="部署前的项目配置"></a>部署前的项目配置</h3><p>Django 项目中会有一些 CSS、JavaScript 等静态文件，为了能够方便地让 Nginx 处理这些静态文件的请求，我们把项目中的全部静态文件收集到一个统一的目录下，这个目录通常位于 Django 项目的根目录，并且命名为 static。为了完成这些任务，需要在项目的配置文件里做一些必要的配置：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">blogproject/settings.py</span><br><span class="line"></span><br><span class="line"><span class="comment">#其他配置</span></span><br><span class="line"></span><br><span class="line">STATIC_URL = <span class="string">'/static/'</span></span><br><span class="line"><span class="comment"># 加入下面的配置</span></span><br><span class="line">STATIC_ROOT = os.path.join(BASE_DIR, <span class="string">'static'</span>)</span><br></pre></td></tr></table></figure>
<p>STATIC_ROOT 指明了静态文件的收集目录，即项目根目录（BASE_DIR）下的 static 文件夹。</p>
<p>为了安全起见，在生产环境下需要关闭 <code>DEBUG</code> 选项以及设置允许访问的域名。打开 settings.py 文件，找到 <code>DEBUG</code> 和 <code>ALLOWED_HOSTS</code> 这两个选项，将它们设置成如下的值：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">blogproject/settings.py</span><br><span class="line"></span><br><span class="line">DEBUG = <span class="literal">False</span></span><br><span class="line">ALLOWED_HOSTS = [<span class="string">'127.0.0.1'</span>, <span class="string">'localhost '</span>, <span class="string">'.ikaros.xin'</span>]</span><br></pre></td></tr></table></figure>
<p><code>ALLOWED_HOSTS</code> 是允许访问的域名列表，127.0.0.1 和 localhost 是本地访问的域名，.ikaros.xin 是访问服务器的域名（<strong>这里换成你自己的域名</strong>）。域名前加一个点表示允许访问该域名下的子域名，比如 <a href="http://www.ikaros.xin、test.ikaros.xin" target="_blank" rel="noopener">www.ikaros.xin、test.ikaros.xin</a> 等二级域名同样允许访问。如果不加前面的点则只允许访问 ikaros.xin。</p>
<p>项目还会依赖一些第三方 Python 库，为了方便在服务器上一次性安装，我们将全部依赖写入一个叫 requirements.txt 的文本文件中。激活<strong>本地的虚拟环境</strong>（如果你使用了虚拟环境的话），并进入项目的根目录，运行 <code>pip freeze &gt; requirements.txt</code> 命令，<em>我这里在本地环境win10下使用项目软件Pycharm，在项目终端运行：</em></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">E:\Python\ikarosblog&gt;</span><br><span class="line">pip freeze &gt; requirements.txt</span><br></pre></td></tr></table></figure>
<p>这时项目根目录下会生成了一个 requirements.txt 的文本文件，其内容记录了项目的全部依赖。</p>
<h3 id="上传代码到服务器"><a href="#上传代码到服务器" class="headerlink" title="上传代码到服务器"></a>上传代码到服务器</h3><h4 id="将代码上传到GitHub"><a href="#将代码上传到GitHub" class="headerlink" title="将代码上传到GitHub"></a>将代码上传到GitHub</h4><p>将代码上传到 GitHub 等代码托管平台，这样我们就可以方便地把代码拉取到服务器了。Git 和 GitHub 的使用相信你已经很熟悉了，这里就不赘述过程。如果不知道如何使用地话可以自行百度相关教程，参考：<a href="https://www.cnblogs.com/cxk1995/p/5800196.html" target="_blank" rel="noopener">使用git将项目上传到github（最简单方法）</a></p>
<p><strong>注意数据库文件不要上传！</strong></p>
<h4 id="使用FTP上传代码"><a href="#使用FTP上传代码" class="headerlink" title="使用FTP上传代码"></a>使用FTP上传代码</h4><p>如果实在没有使用过GitHub，或者嫌麻烦，我推荐一种懒人方法–使用<strong>WinSCP</strong>。</p>
<p>WinSCP是一个Windows环境下使用<a href="https://baike.baidu.com/item/SSH/5400403" target="_blank" rel="noopener">SSH</a>的开源图形化SFTP客户端。同时支持SCP协议。它的主要功能就是在本地与远程计算机间安全的复制文件。WinSCP也可以链接其他系统,比如Linux系统。</p>
<p>自行百度下载WinSCP客户端，连接你的服务器，成功登陆服务器后，你能够以一种图形化的界面看到你服务器的文件和目录。上传代码也非常简单，直接将本地的代码项目拖到WinSCP下对应的服务器目录里就完成了。</p>
<p>是不是非常简单！同样只是上传代码，WinSCP要比GitHub方便的多。</p>
<h3 id="设置服务器目录结构"><a href="#设置服务器目录结构" class="headerlink" title="设置服务器目录结构"></a>设置服务器目录结构</h3><p>接下来需要把代码上传到服务器了。我服务器上存放代码的目录结构是这样的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">/home/yangxg/</span><br><span class="line">    sites/</span><br><span class="line">        demo.zmrenwu.com/</span><br><span class="line">            env/</span><br><span class="line">            django-blog-tutorial/</span><br></pre></td></tr></table></figure>
<p>一台服务器可能部署多个网站，所有网站代码都放在 sites/ 目录下。ikaros.xin 这个文件夹以网站的域名命名，便于区分。env/ 是 python 虚拟环境目录。ikarosblog/ 是 Django 博客项目目录。</p>
<p>因此先来创建这个目录结构，<strong>注意目录名替换为你自己的域名，以后涉及到 ikaros.xin的地方通常都要替换你自己的域名，后面就不再一一指出了</strong>，运行下面的命令:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">root@localhost:~$ mkdir -p ~/sites/ikaros.xin</span><br></pre></td></tr></table></figure>
<p>这里 ~ 代表当前用户的 home 目录，即 /home/django/。</p>
<p>接下来创建虚拟环境，先进入到 ikaros.xin 目录下，然后运行 virtualenv 命令创建虚拟环境：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">root@localhost:~$ cd ~/sites/ikaros.xin</span><br><span class="line">root@localhost:~/sites/ikaros.xin$ virtualenv --python=python3 env</span><br></pre></td></tr></table></figure>
<p>注意这里使用 –python=python3 来指定克隆 Python3 的环境。因为 ubuntu 系统默认安装了 Python2，如果不特别指定的话 Virtualenv 默认克隆的是 Python2 的环境。</p>
<p>检查一下虚拟环境是否创建成功，运行 ls 命令列出当前目录下的文件和文件夹，看到 env 这个文件夹说明虚拟环境创建成功。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">root@localhost:~/sites/ikaros.xin$ ls</span><br><span class="line">env</span><br></pre></td></tr></table></figure>
<p>接着再从代码仓库把项目代码拉取过来，把 git clone 后的地址换成你自己的 GitHub 仓库地址！</p>
<p><strong>或者使用WinSCP拖取项目代码到ikaros.xin文件夹下。</strong></p>
<p>运行 ls 命令检查一下是否拉取成功：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">root@localhost:~/sites/ikaros.xin$ ls</span><br><span class="line">env ikarosblog</span><br></pre></td></tr></table></figure>
<p>我们看到多了一个文件夹ikarosblog（文件夹名称又你的项目文件名或者GitHub仓库名字决定），说明拉取成功。</p>
<h3 id="安装项目依赖"><a href="#安装项目依赖" class="headerlink" title="安装项目依赖"></a>安装项目依赖</h3><p>激活虚拟环境，再进入到项目根目录，即 requirements.txt 所在的目录，安装项目的全部依赖：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">root@localhost:~/sites/ikaros.xin$ source env/bin/activate</span><br><span class="line">(env)root@localhost:~/sites/ikaros.xin$ cd ikarosblog/</span><br><span class="line">(env)root@localhost:~/sites/ikaros.xin/ikarosblog$ pip install -r requirements.txt</span><br></pre></td></tr></table></figure>
<h3 id="收集静态命令"><a href="#收集静态命令" class="headerlink" title="收集静态命令"></a>收集静态命令</h3><p>虚拟环境下继续运行 <code>python manage.py collectstatic</code> 命令收集静态文件到 static 目录下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(env)root@localhost:~/sites/ikaros.xin/ikarosblog$ python manage.py collectstatic</span><br></pre></td></tr></table></figure>
<h3 id="生成数据库"><a href="#生成数据库" class="headerlink" title="生成数据库"></a>生成数据库</h3><p>虚拟环境下继续运行 <code>python manage.py migrate</code> 命令创建数据库文件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(env)root@localhost:~/sites/ikaros.xin/ikarosblog$ python manage.py migrate</span><br></pre></td></tr></table></figure>
<p>注意：如果你的网站使用的是MySQL数据库，则需要安装Ubuntu下的MySQL。详情可参考我的另一篇文章：Ubuntu 16.04的MySQL安装与配置</p>
<h3 id="创建超级用户"><a href="#创建超级用户" class="headerlink" title="创建超级用户"></a>创建超级用户</h3><p>虚拟环境下继续运行 <code>python manage.py createsuperuser</code> 命令创建一个超级用户，方便我们进入 Django 管理后台。这和本地开发时是一样的。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(env)root@localhost:~/sites/ikaros.xin/ikarosblog$ python manage.py createsuperuser</span><br></pre></td></tr></table></figure>
<h2 id="配置-Nginx"><a href="#配置-Nginx" class="headerlink" title="配置 Nginx"></a>配置 Nginx</h2><p>下面我们来配置Nginx用于处理用户请求</p>
<p>先在服务器的 /etc/nginx/sites-available/ 目录下新建一个配置文件，文件名我一般就设置为域名。写上下面的配置内容：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">/etc/nginx/sites-available/ikaros.xin</span><br><span class="line"></span><br><span class="line">server &#123;</span><br><span class="line">    charset utf-8;</span><br><span class="line">    listen 80;</span><br><span class="line">    #服务的域名为 ikaros.xin</span><br><span class="line">    server_name ikaros.xin;</span><br><span class="line"></span><br><span class="line">    location /static &#123;</span><br><span class="line">    #所有URL 带有 /static 的请求均由 Nginx 处理，alias 指明了静态文件的存放目录。</span><br><span class="line">        alias /home/django/sites/ikaros.xin/ikarosblog/static; </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    location / &#123;</span><br><span class="line">    #其它请求转发给 Django 处理。proxy_pass 后面使用了 unix 套接字，其作用是防止端口冲突，这里就不再详述。</span><br><span class="line">        proxy_set_header Host $host;</span><br><span class="line">        proxy_pass http://unix:/tmp/ikaros.xin.socket;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们可以选择使用vi编辑器在服务器端写文件，vi编辑器的使用方法百度可查，只需要掌握一点点简单的用法就行了。</p>
<p>当然我们还是可以使用WinSCP来新建文件和写文件，毕竟可视化的界面总比在服务器端写命令好多了，使用WinSCP就和在Windows下一样，这里就不多讲了。</p>
<p>我们在 /etc/nginx/sites-available/ 放置了配置文件，接下来需要创建一个符号链接，把这个配置文件加入到启用的网站列表中去，被启用网站的目录在 /etc/nginx/sites-enabled/，你可以理解为从 sites-available/ 目录下发送了一个配置文件的快捷方式到 sites-enabled/ 目录。具体命令如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(env)root@localhost:~/sites/ikaros.xin/ikarosblog$ sudo ln -s /etc/nginx/sites-available/ikaros.xin /etc/nginx/sites-enabled/ikaros.xin</span><br></pre></td></tr></table></figure>
<p>执行完符号连接后，我们可以发现在 /etc/nginx/sites-available/ 和/etc/nginx/sites-enabled/文件夹下，都各自有两个相同的配置文件一个default文件和一个我们写的ikaros.xin的配置文件。这时我们需要删除系统默认的default文件，不然这个default文件会导致我们自己写的配置文件失效。把default文件删掉就可以正常被nginx代理过去了。</p>
<h2 id="使用Gunicorn"><a href="#使用Gunicorn" class="headerlink" title="使用Gunicorn"></a>使用Gunicorn</h2><p>Gunicorn 一般用来管理多个进程，有进程挂了Gunicorn 可以把它拉起来，防止服务器长时间停止服务，还可以动态调整 worker 的数量，请求多的时候增加 worker 的数量，请求少的时候减少。</p>
<p>在虚拟环境下，安装 Gunicorn：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(env)root@localhost:~/sites/ikaros.xin/ikarosblog$ pip install gunicorn</span><br></pre></td></tr></table></figure>
<p>用 Gunicorn 启动服务器进程：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(env)root@localhost:~/sites/ikaros.xin/ikarosblog$ gunicorn --bind unix:/tmp/ikaros.xin.socket blogproject.wsgi:application</span><br></pre></td></tr></table></figure>
<p>浏览器输入域名，可以看到访问成功了！</p>
<h3 id="自动启动-Gunicorn"><a href="#自动启动-Gunicorn" class="headerlink" title="自动启动 Gunicorn"></a>自动启动 Gunicorn</h3><p>现在 Gunicorn 是我们手工启动的，万一哪天服务器崩溃重启了又得重新手工启动。为此我们写一个自动启动脚本，这样当服务器重新启动后，脚本会帮我们重启 Gunicorn。先按 Ctrl + c 停止刚才启动的服务器进程。</p>
<p>写一个启动脚本，这样当服务器重启后能自动引导 Gunicorn 的启动。首先在/lib/systemd/system/目录下，创建服务脚本 bg.service，必须以service结尾：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"># /lib/systemd/system/bg.service</span><br><span class="line"></span><br><span class="line">[Unit]</span><br><span class="line">After=syslog.target network.target remote-fs.target nss-lookup.target</span><br><span class="line">[Service]</span><br><span class="line"># 你的用户</span><br><span class="line">User=django</span><br><span class="line"># 你的目录</span><br><span class="line">WorkingDirectory=/home/django/sites/ikaros.xin/ikarosblog</span><br><span class="line"># gunicorn启动命令</span><br><span class="line">ExecStart=/home/django/sites/ikaros.xin/env/bin/gunicorn --bind unix:/tmp/ikaros.xin.socket blogproject.wsgi:application</span><br><span class="line">Restart=on-failure</span><br><span class="line">[Install]</span><br><span class="line">WantedBy=multi-user.target</span><br></pre></td></tr></table></figure>
<p>然后设置让脚本开机自动启动</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">root@localhost:~$ sudo systemctl enable bg.service</span><br></pre></td></tr></table></figure>
<p>拓展 <em>常用命令</em></p>
<ul>
<li><em>重新加载service文件：systemctl daemon-reload</em></li>
<li><em>启动一个服务：systemctl start bg.service</em>  </li>
<li><em>关闭一个服务：systemctl stop bg.service</em>  </li>
<li><em>重启一个服务：systemctl restart bg.service</em>  d</li>
<li><em>显示一个服务的状态</em>：systemctl status bg.service  </li>
<li><em>在开机时启用一个服务：systemctl enable bg.service</em>  </li>
<li><em>在开机时禁用一个服务：systemctl disable bg.service</em>  </li>
<li><em>查看服务是否开机启动：systemctl is-enabled bg.service</em>  </li>
<li><em>查看已启动的服务列表：systemctl list-unit-files|grep enabled</em></li>
<li><em>查看启动失败的服务列表：systemctl –failed</em></li>
</ul>
<p>以后如果更新了代码，只要运行下面的命令重启一下 Nginx 和 Gunicorn 就可以使新的代码生效了：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sudo service nginx reload</span><br><span class="line">sudo systemctl enable bg.service</span><br></pre></td></tr></table></figure>
<h2 id="心得总结"><a href="#心得总结" class="headerlink" title="心得总结"></a>心得总结</h2><p>这篇文章是基于我自己部署这个网站后想写的第一篇正式的干货，即时大部分是基于网上的教程，但是经过我的踩坑，已经排除了这篇教程绝大多数的不足之处。</p>
<p>如果遇到问题，请通过一下方式寻求帮助：</p>
<ul>
<li>在下方评论区留言。</li>
<li>将问题的详情描述以邮件的方式发送至<a href="mailto:ikarosyu@Gmail.com" target="_blank" rel="noopener">ikarosyu@Gmail.com</a>，随缘回复（如果我能看见的话，毕竟穷学生没钱搭SS了）</li>
</ul>
<center>– EOF –</center>
      
    </div>

    

    
    
    

    

    
      
    
    

    
      <div>
        




  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>ikaros</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="http://ikarosyu.gitee.io/ikaros/2019/02/28/Nginx-Gunicorn/" title="基于Nginx和Gunicorn自动化部署Django博客网站（心得教程）">http://ikarosyu.gitee.io/ikaros/2019/02/28/Nginx-Gunicorn/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-CN" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/ikaros/tags/Python/" rel="tag"># Python</a>
          
            <a href="/ikaros/tags/Linux/" rel="tag"># Linux</a>
          
            <a href="/ikaros/tags/learn/" rel="tag"># learn</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/ikaros/2019/02/28/congratulate/" rel="next" title="Congratulate">
                <i class="fa fa-chevron-left"></i> Congratulate
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/ikaros/2019/03/04/shilian/" rel="prev" title="如何快速走出失恋">
                如何快速走出失恋 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/ikaros/images/Misaka.png" alt="ikaros">
            
              <p class="site-author-name" itemprop="name">ikaros</p>
              <div class="site-description motion-element" itemprop="description">like sunday like rain like apple and cinnamon</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/ikaros/archives/">
                
                    <span class="site-state-item-count">14</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/ikaros/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/ikaros/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">13</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/ikaros/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/ikarosyu" title="GitHub &rarr; https://github.com/ikarosyu" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://ikarosyu@gmail.com" title="E-Mail &rarr; https://ikarosyu@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://twitter.com/ikarosyu" title="Twitter &rarr; https://twitter.com/ikarosyu" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://steamcommunity.com/id/ikarosyu/" title="steam &rarr; https://steamcommunity.com/id/ikarosyu/" rel="noopener" target="_blank"><i class="fa fa-fw fa-steam"></i>steam</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://weibo.com/3024293020/profile?rightmod=1&wvr=6&mod=personinfo&is_all=1" title="Weibo &rarr; https://weibo.com/3024293020/profile?rightmod=1&wvr=6&mod=personinfo&is_all=1" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="http://www.zhihu.com/people/ikaros-48?utm_source=qq&utm_medium=social&utm_oi=740688299089199104" title="知乎 &rarr; http://www.zhihu.com/people/ikaros-48?utm_source=qq&utm_medium=social&utm_oi=740688299089199104" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>知乎</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="/ikaros/assets/qq.jpg" title="QQ &rarr; /assets/qq.jpg"><i class="fa fa-fw fa-qq"></i>QQ</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="/ikaros/assets/wechat.png" title="Wechat &rarr; /assets/wechat.png"><i class="fa fa-fw fa-wechat"></i>Wechat</a>
                </span>
              
            </div>
          

          
             <div class="cc-license motion-element" itemprop="license">
              
              
                
              
              
              
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-CN" class="cc-opacity" rel="noopener" target="_blank"><img src="/ikaros/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
             </div>
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://ikaros149.lofter.com/" title="http://ikaros149.lofter.com/" rel="noopener" target="_blank">ikarosyu</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://sakurabaka.lofter.com/" title="http://sakurabaka.lofter.com/" rel="noopener" target="_blank">sukura</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="//www.google.com" title="//www.google.com">google</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#基于Nginx和Gunicorn自动化部署Django博客网站（心得教程）"><span class="nav-number">1.</span> <span class="nav-text">基于Nginx和Gunicorn自动化部署Django博客网站（心得教程）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#阅前叨逼叨"><span class="nav-number">1.1.</span> <span class="nav-text">阅前叨逼叨</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#首要的准备"><span class="nav-number">1.2.</span> <span class="nav-text">首要的准备</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#服务器"><span class="nav-number">1.2.1.</span> <span class="nav-text">服务器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#域名购买"><span class="nav-number">1.2.2.</span> <span class="nav-text">域名购买</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#搭建服务器"><span class="nav-number">1.3.</span> <span class="nav-text">搭建服务器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#安装软件"><span class="nav-number">1.3.1.</span> <span class="nav-text">安装软件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#解析域名到服务器的IP地址"><span class="nav-number">1.3.2.</span> <span class="nav-text">解析域名到服务器的IP地址</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#启动Nginx服务"><span class="nav-number">1.3.3.</span> <span class="nav-text">启动Nginx服务</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#代码的部署"><span class="nav-number">1.4.</span> <span class="nav-text">代码的部署</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#部署前的项目配置"><span class="nav-number">1.4.1.</span> <span class="nav-text">部署前的项目配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#上传代码到服务器"><span class="nav-number">1.4.2.</span> <span class="nav-text">上传代码到服务器</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#将代码上传到GitHub"><span class="nav-number">1.4.2.1.</span> <span class="nav-text">将代码上传到GitHub</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用FTP上传代码"><span class="nav-number">1.4.2.2.</span> <span class="nav-text">使用FTP上传代码</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#设置服务器目录结构"><span class="nav-number">1.4.3.</span> <span class="nav-text">设置服务器目录结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#安装项目依赖"><span class="nav-number">1.4.4.</span> <span class="nav-text">安装项目依赖</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#收集静态命令"><span class="nav-number">1.4.5.</span> <span class="nav-text">收集静态命令</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#生成数据库"><span class="nav-number">1.4.6.</span> <span class="nav-text">生成数据库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建超级用户"><span class="nav-number">1.4.7.</span> <span class="nav-text">创建超级用户</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配置-Nginx"><span class="nav-number">1.5.</span> <span class="nav-text">配置 Nginx</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用Gunicorn"><span class="nav-number">1.6.</span> <span class="nav-text">使用Gunicorn</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#自动启动-Gunicorn"><span class="nav-number">1.6.1.</span> <span class="nav-text">自动启动 Gunicorn</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#心得总结"><span class="nav-number">1.7.</span> <span class="nav-text">心得总结</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ikaros</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">站点总字数：</span>
    
    <span title="站点总字数">50k</span>
  

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    
    <span title="站点阅读时长">46 分钟</span>
  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.0.1</div>




        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      网站总访客数 <span class="busuanzi-value" id="busuanzi_value_site_uv"></span> 人次. |
    </span>
  

  
    <span class="post-meta-divider">|</span>
  

  
    <span class="site-pv" title="总访问量">
      &nbsp;<i class="fa fa-eye"></i>
      总访问量 <span class="busuanzi-value" id="busuanzi_value_site_pv"></span> 次.
    </span>

</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/ikaros/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/ikaros/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/ikaros/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/ikaros/js/src/utils.js?v=7.0.1"></script>

  <script src="/ikaros/js/src/motion.js?v=7.0.1"></script>



  
  


  <script src="/ikaros/js/src/affix.js?v=7.0.1"></script>

  <script src="/ikaros/js/src/schemes/pisces.js?v=7.0.1"></script>




  
  <script src="/ikaros/js/src/scrollspy.js?v=7.0.1"></script>
<script src="/ikaros/js/src/post-details.js?v=7.0.1"></script>



  


  <script src="/ikaros/js/src/next-boot.js?v=7.0.1"></script>


  

  

  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/ikaros/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

  

  

  

  

  

  
<script>
  $('.highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
